package com.ssy.lingxi.platform.manage.serviceimpl.mobile;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.manage.ShopEnvironmentEnum;
import com.ssy.lingxi.common.constant.manage.ShopPropertyEnum;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.model.app.AppSelfBusinessShopListRespVO;
import com.ssy.lingxi.platform.manage.api.model.app.AppShopTypeSelectVO;
import com.ssy.lingxi.platform.manage.api.model.app.AppShopVO;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.ShopVO;
import com.ssy.lingxi.platform.manage.api.model.vo.site.SiteShopVO;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.base.*;
import com.ssy.lingxi.platform.manage.model.request.shop.ShopAllReq;
import com.ssy.lingxi.platform.manage.model.response.SelfBusinessShopListResp;
import com.ssy.lingxi.platform.manage.repository.*;
import com.ssy.lingxi.platform.manage.service.mobile.IShopMobileService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * mobile - 商城 - 业务实现层
 *
 * @author fhj
 * @version 2.0.0
 * @date 2021/09/27
 */
@Service
public class ShopMobileServiceImpl implements IShopMobileService {

    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private ShopRepository shopRepository;
    @Resource
    private SiteShopRepository siteShopRepository;
    @Resource
    private ShopRuleDetailRepository shopRuleDetailRepository;
    @Resource
    private SiteRepository siteRepository;
    @Resource
    private ShopRuleRepository shopRuleRepository;


    @Override
    public Wrapper<List<Shop>> startPageShopList(Long siteId) {
        //校验
        if (siteId == null) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SITE_ID_CANNOT_BE_EMPTY);
        }
        //根据站点ID获取站点关联的商城
        List<SiteShop> siteShopList = siteShopRepository.findBySiteId(siteId);
        if (CollectionUtil.isEmpty(siteShopList)) {
            return Wrapper.success(new ArrayList<>());
        }

        //获取商城
        List<Shop> shopList = shopRepository.findAllByIdInAndEnvironmentAndState(
                siteShopList.stream().map(SiteShop::getShopId).collect(Collectors.toList()),
                ShopEnvironmentEnum.APP.getCode(),
                CommonBooleanEnum.YES.getCode()
        );

        //只获取企业商城、渠道商城、渠道自有商城
        return Wrapper.success(
                shopList.stream().filter(a ->
                        ShopTypeEnum.checkEnterpriseOrChannelOrChannelSelf(a.getType())
                ).collect(Collectors.toList())
        );
    }

    @Override
    public Wrapper<List<SelfBusinessShopListResp>> selfBusinessShopList(Long shopId) {
        //校验
        if (shopId == null) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SHOP_ID_CANNOT_BE_EMPTY);
        }

        //根据商城ID获取商城规则详情
        List<ShopRuleDetail> list = shopRuleDetailRepository.findByShopIdAndState(shopId, CommonBooleanEnum.YES.getCode(), Sort.by("id").descending());
        if (CollectionUtil.isEmpty(list)) {
            return Wrapper.success(new ArrayList<>());
        }

        //组装
        List<SelfBusinessShopListResp> respList = list.stream().map(a -> {
            SelfBusinessShopListResp resp = new SelfBusinessShopListResp();
            resp.setId(a.getShopId());
            resp.setShopRuleDetailId(a.getId());
            resp.setName(a.getName());
            resp.setProperty(a.getProperty());
            resp.setLogoUrl(a.getLogoUrl());
            resp.setUrl(a.getUrl());
            resp.setMemberName(a.getShopRule().getMemberName() + "的" + a.getName());
            resp.setMemberId(a.getShopRule().getMemberId());
            resp.setMemberRoleId(a.getShopRule().getMemberRoleId());
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(respList);
    }

    @Override
    public Wrapper<List<Shop>> all(ShopAllReq req) {
        //根据站点ID获取站点关联的商城ID
        List<SiteShop> siteShopList = siteShopRepository.findBySiteId(req.getSiteId());
        if (CollectionUtil.isEmpty(siteShopList)) {
            return Wrapper.success(new ArrayList<>());
        }
        List<Long> shopIdList = siteShopList.stream().map(SiteShop::getShopId).collect(Collectors.toList());

        //根据条件获取商城
        QShop shop = QShop.shop;

        //条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(shop.state.eq(CommonBooleanEnum.YES.getCode()));
        predicates.and(shop.id.in(shopIdList));

        //商城环境
        if (req.getEnvironment() != null) {
            predicates.and(shop.environment.eq(req.getEnvironment()));
        }
        //商城类型
        if (req.getType() != null) {
            predicates.and(shop.type.eq(req.getType()));
        }

        //获取商城
        JPAQuery<Shop> jpaQuery = jpaQueryFactory.select(shop).from(shop).where(predicates);
        List<Shop> list = jpaQuery.orderBy(shop.id.asc()).fetch();
        //如果传了会员id和角色id就取该值去查找所属自营商城
        if (req.getMemberId() != null && req.getMemberId() > 0 && req.getRoleId() != null && req.getRoleId() > 0) {
            //获取全部自营商城
            List<Long> selfShopIds = list.stream().filter(p -> CommonBooleanEnum.YES.getCode().equals(p.getIsDefault())).map(Shop::getId).collect(Collectors.toList());
            if (selfShopIds.size() > 0) {
                QShopRule qShopRule = QShopRule.shopRule;
                QShopRuleDetail qShopRuleDetail = QShopRuleDetail.shopRuleDetail;
                List<ShopRuleDetail> detailList = jpaQueryFactory.from(qShopRule)
                        .select(qShopRuleDetail)
                        .join(qShopRuleDetail).on(qShopRule.id.eq(qShopRuleDetail.shopRule.id))
                        .where(qShopRule.memberId.eq(req.getMemberId()).and(qShopRule.memberRoleId.eq(req.getRoleId())))
                        .where(qShopRuleDetail.state.eq(CommonBooleanEnum.YES.getCode()))
                        .orderBy(qShopRuleDetail.shopId.asc())
                        .fetch();
                Map<Long, ShopRuleDetail> shopNameMap = detailList.stream().collect(Collectors.toMap(ShopRuleDetail::getShopId, ShopRuleDetail -> ShopRuleDetail));
                list.stream().filter(p -> shopNameMap.containsKey(p.getId())).forEach(p -> {
                    ShopRuleDetail shopRuleDetail = shopNameMap.get(p.getId());
                    p.setId(shopRuleDetail.getId());
                    p.setName(shopRuleDetail.getName());
                });
            }
        }
        return Wrapper.success(list);
    }

    @Override
    public Wrapper<Integer> checkShopMemberOperate(Long shopId) {
        //校验
        if (shopId == null) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SHOP_ID_CANNOT_BE_EMPTY);
        }
        //大于1000的是自营商城,
        if (shopId < 1000) {
            Shop shop = shopRepository.findById(shopId).orElse(null);
            if (shop == null) {
                return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_DATA_RECORD_DOES_NOT_EXIST);
            }
            return Wrapper.success(shop.getMemberOperate());
        } else {
            ShopRuleDetail shopRuleDetail = shopRuleDetailRepository.findById(shopId).orElse(null);
            if (shopRuleDetail == null) {
                return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_DATA_RECORD_DOES_NOT_EXIST);
            }
            return Wrapper.success(shopRuleDetail.getMemberOperate());
        }


    }

    @Override
    public Wrapper<List<SiteShopVO>> siteShopListByType(Integer type) {
        List<SiteShopVO> siteShopVOS;
        //获取所有站点
        List<Site> siteList = siteRepository.findAll();
        if (type != null) {
            //获取所有站点Id
            List<Long> siteIds = siteList.stream().map(Site::getId).collect(Collectors.toList());
            //站点所关联的商城
            List<SiteShop> siteShopList = siteShopRepository.findAllBySiteIdIn(siteIds);
            //获取商城
            List<Shop> shopList = shopRepository.findAllByIdInAndEnvironmentAndState(
                    siteShopList.stream().map(SiteShop::getShopId).collect(Collectors.toList()),
                    type,
                    CommonBooleanEnum.YES.getCode()
            );
            siteShopVOS = siteList.stream().map(site -> {
                SiteShopVO siteShopVO = new SiteShopVO();
                siteShopVO.setId(site.getId());
                siteShopVO.setSiteName(site.getName());
                //获取该站点下的商城id集合
                List<Long> shopIds = siteShopList.stream().filter(s -> s.getSiteId().equals(site.getId())).map(SiteShop::getShopId).collect(Collectors.toList());
                siteShopVO.setShopList(shopList.stream().filter(shop -> shopIds.contains(shop.getId())).map(shop -> {
                    ShopVO shopVO = new ShopVO();
                    BeanUtils.copyProperties(shop, shopVO);
                    return shopVO;
                }).collect(Collectors.toList()));
                return siteShopVO;
            }).collect(Collectors.toList());
        } else {
            //获取所有站点Id
            List<Long> siteIds = siteList.stream().map(Site::getId).collect(Collectors.toList());
            //站点所关联的商城
            List<SiteShop> siteShopList = siteShopRepository.findAllBySiteIdIn(siteIds);
            //获取商城
            List<Shop> shopList = shopRepository.findAllByIdInAndState(
                    siteShopList.stream().map(SiteShop::getShopId).collect(Collectors.toList()),
                    CommonBooleanEnum.YES.getCode()
            );
            siteShopVOS = siteList.stream().map(site -> {
                SiteShopVO siteShopVO = new SiteShopVO();
                siteShopVO.setId(site.getId());
                siteShopVO.setSiteName(site.getName());
                //获取该站点下的商城id集合
                List<Long> shopIds = siteShopList.stream().filter(s -> s.getSiteId().equals(site.getId())).map(SiteShop::getShopId).collect(Collectors.toList());
                siteShopVO.setShopList(shopList.stream().filter(shop -> shopIds.contains(shop.getId())).map(shop -> {
                    ShopVO shopVO = new ShopVO();
                    BeanUtils.copyProperties(shop, shopVO);
                    return shopVO;
                }).collect(Collectors.toList()));
                return siteShopVO;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(siteShopVOS);
    }

    @Override
    public Wrapper<List<AppShopTypeSelectVO>> appShopTypeSelect(Integer environment) {
        //数据返回实体类
        List<AppShopTypeSelectVO> appShopTypeSelectVos = new ArrayList<>();
        //1.查出全部有效的站点
        List<Site> sites = siteRepository.findByState(1);
        if (CollectionUtil.isNotEmpty(sites)) {
            appShopTypeSelectVos = sites.stream().map(site -> {
                AppShopTypeSelectVO appShopTypeSelectVo = new AppShopTypeSelectVO();
                BeanUtils.copyProperties(site, appShopTypeSelectVo);
                //1-1 获取每个站点所关联的商城id
                List<SiteShop> siteShops = siteShopRepository.findBySiteId(site.getId());
                if (CollectionUtil.isNotEmpty(siteShops)) {
                    List<Long> shopIds = siteShops.stream().map(SiteShop::getShopId).collect(Collectors.toList());
                    //2.获取全部有效的,App/小程序 环境且为企业商城,渠道商城,渠道自有商城的商城
                    List<? extends Serializable> collect = Stream.of(ShopTypeEnum.ENTERPRISE.getCode(), ShopTypeEnum.CHANNEL.getCode(), ShopTypeEnum.CHANNEL_SELF.getCode()).collect(Collectors.toList());
                    List<Shop> shops = shopRepository.findAllByIdInAndEnvironmentAndStateAndTypeIn(shopIds, environment, CommonBooleanEnum.YES.getCode(), collect);
                    //2-1.对企业商城,渠道商城,渠道自有商城进行处理
                    if (CollectionUtil.isNotEmpty(shops)) {
                        List<AppShopVO> appShopVOS = new ArrayList<>();
                        //3-1 获取全部企业商城
                        List<Shop> enterprise = shops.stream().filter(shop -> shop.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())).collect(Collectors.toList());
                        //3-1-1
                        if (CollectionUtil.isNotEmpty(enterprise)) {
                            //判断是否有默认商城
                            Shop shop = enterprise.stream().filter(e -> e.getIsDefault().equals(CommonBooleanEnum.YES.getCode())).findFirst().orElse(null);
                            //如果为null,直接返回全部
                            if (shop == null) {
                                List<ShopVO> shopVOS = enterprise.stream().map(a -> {
                                    ShopVO shopVO = new ShopVO();
                                    BeanUtils.copyProperties(a, shopVO);
                                    return shopVO;
                                }).collect(Collectors.toList());
                                appShopVOS.add(new AppShopVO(ShopTypeEnum.ENTERPRISE.getCode(), shopVOS));
                            } else {
                                //如果默认商城是b端/c端商城,则直接返回
                                if (Stream.of(ShopPropertyEnum.UNION_B.getCode(), ShopPropertyEnum.UNION_C.getCode()).collect(Collectors.toList()).contains(shop.getProperty()) && shop.getSelf().equals(EnableDisableStatus.DISABLE.getCode())) {
                                    ShopVO shopVO = new ShopVO();
                                    BeanUtils.copyProperties(shop, shopVO);
                                    List<ShopVO> shopVOS = new ArrayList<>();
                                    shopVOS.add(shopVO);
                                    appShopVOS.add(new AppShopVO(ShopTypeEnum.ENTERPRISE.getCode(), shopVOS));
                                } else {
                                    //获取自营商城
                                    List<AppSelfBusinessShopListRespVO> appSelfBusinessShopList = AppSelfBusinessShopList(shopIds, environment).getData();
                                    if (CollectionUtil.isNotEmpty(appSelfBusinessShopList)) {
                                        ShopVO shopVO = new ShopVO();
                                        BeanUtils.copyProperties(shop, shopVO);
                                        shopVO.setSelfBusinessShopListRespVOS(appSelfBusinessShopList);
                                        List<ShopVO> shopVOS = new ArrayList<>();
                                        shopVOS.add(shopVO);
                                        appShopVOS.add(new AppShopVO(ShopTypeEnum.ENTERPRISE.getCode(), shopVOS));
                                    }
                                }
                            }
                        }
                        //3-2 获取全部渠道商城
                        List<Shop> channel = shops.stream().filter(shop -> shop.getType().equals(ShopTypeEnum.CHANNEL.getCode())).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(channel)) {
                            List<ShopVO> shopVOS = channel.stream().map(c -> {
                                ShopVO shopVO = new ShopVO();
                                BeanUtils.copyProperties(c, shopVO);
                                return shopVO;
                            }).collect(Collectors.toList());
                            appShopVOS.add(new AppShopVO(ShopTypeEnum.CHANNEL.getCode(), shopVOS));
                        }
                        //3-3 获取全部渠道自有商城
                        List<Shop> channelSelf = shops.stream().filter(shop -> shop.getType().equals(ShopTypeEnum.CHANNEL_SELF.getCode())).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(channelSelf)) {
                            List<ShopVO> shopVOS = channelSelf.stream().map(c -> {
                                ShopVO shopVO = new ShopVO();
                                BeanUtils.copyProperties(c, shopVO);
                                return shopVO;
                            }).collect(Collectors.toList());
                            appShopVOS.add(new AppShopVO(ShopTypeEnum.CHANNEL_SELF.getCode(), shopVOS));
                        }
                        appShopTypeSelectVo.setAppShopVOS(appShopVOS);
                    }
                }
                return appShopTypeSelectVo;
            }).collect(Collectors.toList());
        }

        return Wrapper.success(appShopTypeSelectVos);
    }

    private Wrapper<List<AppSelfBusinessShopListRespVO>> AppSelfBusinessShopList(List<Long> shopIds, Integer environment) {
        List<AppSelfBusinessShopListRespVO> respList = new ArrayList<>();
        //平台后台--系统管理--商城规则配置中的所有会员及会员下的商城数据且商城环境为APP且为默认商城
        List<ShopRule> shopRules = shopRuleRepository.findByStatus(CommonBooleanEnum.YES.getCode());
        if (CollectionUtil.isNotEmpty(shopRules)) {
            respList = shopRules.stream().map(a -> {
                //获取每个会员下的全部自营商城
                List<ShopRuleDetail> detailList = a.getShopList();
                if (CollectionUtil.isNotEmpty(detailList)) {
                    //获取当前站点下的全部自营商城
                    detailList = detailList.stream().filter(shopRuleDetail -> shopRuleDetail != null && shopIds.contains(shopRuleDetail.getShopId()) && shopRuleDetail.getEnvironment().equals(environment)).collect(Collectors.toList());
                    AppSelfBusinessShopListRespVO resp = new AppSelfBusinessShopListRespVO();
                    //判断是否有默认商城
                    ShopRuleDetail shopRuleDetail = detailList.stream().
                            filter(p -> p != null && p.getIsDefault().equals(CommonBooleanEnum.YES.getCode())
                                    && p.getEnvironment().equals(environment)).findFirst().orElse(null);
                    if (shopRuleDetail != null) {
                        resp.setId(shopRuleDetail.getShopId());
                        resp.setShopRuleDetailId(shopRuleDetail.getId());
                        resp.setName(shopRuleDetail.getName());
                        resp.setProperty(shopRuleDetail.getProperty());
                        resp.setLogoUrl(shopRuleDetail.getLogoUrl());
                        resp.setUrl(shopRuleDetail.getUrl());
                        resp.setMemberName(shopRuleDetail.getShopRule().getMemberName() + "的" + shopRuleDetail.getName());
                        resp.setMemberId(shopRuleDetail.getShopRule().getMemberId());
                        resp.setMemberRoleId(shopRuleDetail.getShopRule().getMemberRoleId());
                        resp.setCreateTime(shopRuleDetail.getCreateTime());
                        return resp;
                    } else {
                        //如果没有则获取创建时间最早的那商城
                        shopRuleDetail = detailList.stream().
                                filter(p -> p != null && p.getEnvironment().equals(environment))
                                .min(Comparator.comparing(ShopRuleDetail::getCreateTime)).orElse(null);
                        if (shopRuleDetail != null) {
                            resp.setId(shopRuleDetail.getShopId());
                            resp.setShopRuleDetailId(shopRuleDetail.getId());
                            resp.setName(shopRuleDetail.getName());
                            resp.setProperty(shopRuleDetail.getProperty());
                            resp.setLogoUrl(shopRuleDetail.getLogoUrl());
                            resp.setUrl(shopRuleDetail.getUrl());
                            resp.setMemberName(shopRuleDetail.getShopRule().getMemberName() + "的" + shopRuleDetail.getName());
                            resp.setMemberId(shopRuleDetail.getShopRule().getMemberId());
                            resp.setMemberRoleId(shopRuleDetail.getShopRule().getMemberRoleId());
                            resp.setCreateTime(shopRuleDetail.getCreateTime());
                        }
                        return resp;
                    }
                } else {
                    return new AppSelfBusinessShopListRespVO();
                }

            }).sorted(Comparator.comparing(AppSelfBusinessShopListRespVO::getCreateTime)).collect(Collectors.toList());
        }
        //倒序返回
        return Wrapper.success(CollectionUtil.reverse(respList.stream().filter(p -> p.getId() != null).collect(Collectors.toList())));
    }
    /*        //根据商城ID获取商城规则详情
        List<ShopRuleDetail> list = shopRuleDetailRepository.findByShopIdAndStateAndEnvironment(null, CommonBooleanEnum.YES.getCode(), ShopEnvironmentEnum.APP.getCode(), Sort.by("id").descending());
        if (CollectionUtil.isEmpty(list)) {
            return Wrapper.success(new ArrayList<>());
        }

        //组装
        List<AppSelfBusinessShopListRespVO> respList = list.stream().map(a -> {
            AppSelfBusinessShopListRespVO resp = new AppSelfBusinessShopListRespVO();
            resp.setId(a.getShopId());
            resp.setName(a.getName());
            resp.setProperty(a.getProperty());
            resp.setLogoUrl(a.getLogoUrl());
            resp.setUrl(a.getUrl());
            resp.setMemberName(a.getShopRule().getMemberName() + "的" + a.getName());
            resp.setMemberId(a.getShopRule().getMemberId());
            resp.setMemberRoleId(a.getShopRule().getMemberRoleId());
            return resp;
        }).collect(Collectors.toList());*/
}
